package com.atsmart.app.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.CellLocation;
import android.util.Log;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.activity.NavActivity;
import com.atsmart.app.model.NumberRequsetInfo;
import com.atsmart.app.model.NumberRequsetListInfo;
import com.atsmart.app.model.NumberResponseInfo;
import com.atsmart.app.model.NumberResponseListInfo;
import com.atsmart.app.model.PositionAttributeInfo;
import com.atsmart.app.receiver.HistoryReceiver;
import com.atsmart.app.receiver.SendReceiver;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.sql.PositionSqlHelper;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.atsmart.log.UserLog;
//import com.atsmart.log.UserLog;
import com.google.json.Gson;

public class infoService extends Service {

	private NumberSqlHelper nsql = null;
	private PowerManager.WakeLock wakeLock = null;
	private static long choosen = 0;
	private static int dur = 0;
	private PositionSqlHelper psql = null;
	public static infoService instance = null; 
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		instance = this;
		try {
			BizApp.getInstance().getmLocationClient().start();
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}
//	这种service并没有单独开一个线程，仍然是主线程，所以，当在里面进行各种耗时操作时，会出现ANR（对Activity和BroadcastReceiver
//	响应时间的限制（Activity对事件响应不超过5秒，BroadcastReceiver执行不超过10秒））。一般耗时操作最好在service中另开一个线程。
//	   所以推荐使用IntentService，IntentService是重新开一个线程来处理需要完成的任务。
//	通过startService启动服务，若服务未启动，会先执行onCreate函数(若服务已启动则不执行此函数)，
//	再执行onStartCommand函数。由此可知多次调用startService传入相同参数不会启动多个服务(onStartCommand函数会执行多次)，
//	所以最终只需要调用一次stopService或stopSelf函数停止服务；我们可以将service的处理逻辑放入onStartCommand函数中。
//	服务一直运行，在程序退出后服务也不会停止，直到stopService或stopSelf函数被调用，当然可能被系统回收。
//	对于onStartCommand的返回值，若返回START_STICKY表示服务通过显式调用启动或停止，若返回START_NOT_STICKY orSTART_REDELIVER_INTENT表示服务仅在有请求发送过来处理时才处于运行状态。
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			wakeLock = acquireWakeLock();
			relesseWakeLock();
			BizApp.getInstance().setSendtime(System.currentTimeMillis());
			PositionAttributeInfo pinfo = null;
			boolean flag = checkSheetTime();
			psql = new PositionSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			pinfo = psql.getAttribute();
			if(BizApp.isWrite){
				UserLog.getInstance().writeFilePosition(" infoservice 取出巡检条件： = " + pinfo.getSheet() + " , " + pinfo.getDur() +" ， 时间： = " +StringUtil.getCurrentTime()+"\n");
			}
//			Log.e("TAG", " infoservice 取出巡检条件： = " + pinfo.getSheet() + " , " + pinfo.getDur());
			if (dur != 0 && dur != pinfo.getDur()) {
				choosen = 0;
			}

			if (choosen % (pinfo.getDur() / 60) == 0) {
				choosen = 0;
			}
		
			dur = pinfo.getDur();

			nsql = new NumberSqlHelper();
			nsql.open(BizApp.getInstance().getSqlHelper());
			Calendar cal1 = Calendar.getInstance();
			if (dur != 0 && flag && choosen % (pinfo.getDur() / 60) == 0) {
				choosen++;
				try {
					if (BizApp.getInstance().keeping) {
						BizApp.getInstance().getmLocationClient().stop();
					}
				} catch (Exception e) {
					//e.printStackTrace();
				}

				wakeLock = acquireWakeLock();
				CellLocation.requestLocationUpdate();
				relesseWakeLock();

				Intent intent1 = new Intent(getApplicationContext(),SendReceiver.class);
				PendingIntent pi1 = PendingIntent.getBroadcast(getApplicationContext(), 1028, intent1, 0);
				AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
				am.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pi1);
			} else {
				choosen++;
			}
			Intent intent2 = new Intent(getApplicationContext(),HistoryReceiver.class);
			PendingIntent pi2 = PendingIntent.getBroadcast(getApplicationContext(), 1028 * 2, intent2, 0);
			AlarmManager amhis = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			amhis.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), pi2);
		} catch (Exception e) {
			//e.printStackTrace();
		}

		return START_NOT_STICKY;
	}

	private void relesseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	private PowerManager.WakeLock acquireWakeLock() {
		try {

			PowerManager localPowerManager = (PowerManager) getSystemService("power");
			if (localPowerManager != null) {
				String str1 = infoService.class.getName();
				PowerManager.WakeLock localWakeLock = null;
			 
				if (android.os.Build.MODEL.equals("HUAWEI Y 220T")
						|| android.os.Build.MODEL.equals("ZTE-U V880")
						|| android.os.Build.MODEL.equals("HUAWEI C8813Q")
						|| android.os.Build.MODEL.equals("ZTE V889D")) {
				 
					localWakeLock = localPowerManager.newWakeLock(
							PowerManager.SCREEN_DIM_WAKE_LOCK
									| PowerManager.ACQUIRE_CAUSES_WAKEUP, str1);
				} else {
					localWakeLock = localPowerManager.newWakeLock(
							PowerManager.PARTIAL_WAKE_LOCK, str1);

				}
				if (localWakeLock != null)
					localWakeLock.acquire();
				if (localWakeLock != null && localWakeLock.isHeld())
					localWakeLock.release();
				return localWakeLock;
			} else {
				return null;
			}

		} catch (Exception localException) {
			localException.printStackTrace();
			return null;
		}

	}

	@Override
	public void onDestroy() {
		if (BizApp.getInstance().getmLocationClient() != null) {
			try {
				BizApp.getInstance().getmLocationClient().stop();
			} catch (Exception e) {
			}

		}
	}

	@Override
	public void onStart(Intent intent, int startid) {
		 acquireWakeLock();

	}

	private boolean checkSheetTime() {
		try {
			BizApp.getInstance().start = false;
			BizApp.getInstance().end = false;
			PositionSqlHelper psql = new PositionSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			PositionAttributeInfo inf = psql.getAttribute();

			int week = 0;
			int hour = 0;
			int min = 0;

			if (inf != null) {

				Calendar c = Calendar.getInstance();
				week = c.get(Calendar.DAY_OF_WEEK) - 1;

				hour = c.get(Calendar.HOUR_OF_DAY);
				min = c.get(Calendar.MINUTE);

				String sheet = inf.sheet;

				int dur = inf.getDur() * 1000;
				// Log.e("dur", dur+"");
				BizApp.getInstance().num = inf.getDur() / 60;

				String[] sheets = sheet.split(";");
				for (int i = 0; i < sheets.length; i++) {
					String weeks = sheets[i];
					String[] weekc = weeks.split(",");
					if (week == Integer.valueOf(weekc[0])) {
						if (Integer.valueOf(weekc[1]) == 1) {
							if (weekc.length == 2) {
								return true;
							}
							if (weekc.length == 6) {
								// return true;
								long ab = getMill(weekc[2], weekc[3])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ab) < dur) {
									BizApp.getInstance().start = true;
								}
								long ac = getMill(weekc[4], weekc[5])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ac) < dur) {
									BizApp.getInstance().end = true;
								}
								if (hour > Integer.valueOf(weekc[2])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[2])
										&& min >= Integer.valueOf(weekc[3])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {

									return true;
								}
							}
							if (weekc.length == 10) {
								// return true;
								long ab = getMill(weekc[2], weekc[3])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ab) < dur) {
									BizApp.getInstance().start = true;
								}
								long ac = getMill(weekc[4], weekc[5])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ac) < dur) {
									BizApp.getInstance().end = true;
								}
								long ad = getMill(weekc[6], weekc[7])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ad) < dur) {
									BizApp.getInstance().start = true;
								}
								long ae = getMill(weekc[8], weekc[9])
										- StringUtil.FormDateToTime(StringUtil
												.getFullReportTime());
								if (Math.abs(ae) < dur) {
									BizApp.getInstance().end = true;
								}
								if (hour > Integer.valueOf(weekc[2])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[2])
										&& min >= Integer.valueOf(weekc[3])
										&& (hour < Integer.valueOf(weekc[4]) || hour == Integer
												.valueOf(weekc[4])
												&& min <= Integer
														.valueOf(weekc[5]))) {
									return true;
								}
								if (hour > Integer.valueOf(weekc[6])
										&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
												.valueOf(weekc[8])
												&& min <= Integer
														.valueOf(weekc[9]))) {
									return true;
								}
								if (hour == Integer.valueOf(weekc[6])
										&& min >= Integer.valueOf(weekc[7])
										&& (hour < Integer.valueOf(weekc[8]) || hour == Integer
												.valueOf(weekc[8])
												&& min <= Integer
														.valueOf(weekc[9]))) {
									return true;
								}
							}
						}
					}
				}
				return false;
			} else {
				return false;
			}

		} catch (Exception e) {
		}
		return false;
	}

	private long getMill(String hour, String min) {
		try {
			String str = StringUtil.getFormTime();
			return StringUtil.FormDateTomill(str + " " + hour + ":" + min);
		} catch (Exception e) {
		}
		return 0;
	}

	private NumberResponseListInfo getNum() {
		try {
			List<NumberResponseInfo> nums = nsql.getNumberInfo();
			NumberRequsetListInfo linums = new NumberRequsetListInfo();
			List<NumberRequsetInfo> lis = new ArrayList<NumberRequsetInfo>();
			for (NumberResponseInfo num : nums) {
				NumberRequsetInfo rt = new NumberRequsetInfo();
				if (num.getLastTime() != 0) {
					rt.setType(num.getType());
					rt.setLastTime(num.getLastTime());
				}
				lis.add(rt);
			}
			linums.setVers(lis);

			return ServiceHelper.getInstance().postData(
					ServiceHost.updateNumberURL(), new Gson().toJson(linums),
					NumberResponseListInfo.class);
		} catch (Exception e) {
			if(PrefsUtils.getURL().equals(StringUtil.URL1)){
				PrefsUtils.setURL(StringUtil.URL2);
			}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
				PrefsUtils.setURL(StringUtil.URL1);
			}
			try{
				List<NumberResponseInfo> nums = nsql.getNumberInfo();
				NumberRequsetListInfo linums = new NumberRequsetListInfo();
				List<NumberRequsetInfo> lis = new ArrayList<NumberRequsetInfo>();
				for (NumberResponseInfo num : nums) {
					NumberRequsetInfo rt = new NumberRequsetInfo();
					if (num.getLastTime() != 0) {
						rt.setType(num.getType());
						rt.setLastTime(num.getLastTime());
					}
					lis.add(rt);
				}
				linums.setVers(lis);

				return ServiceHelper.getInstance().postData(
						ServiceHost.updateNumberURL(), new Gson().toJson(linums),
						NumberResponseListInfo.class);
			}catch (Exception ex) {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				return null;
			}
			
		}
	}


}
